#!/usr/bin/python

##HACKABOT_HELP##
# Say something random! Uses the previous lines as input
# !imitate [nick] [lines]
##HACKABOT_HELP##

import string
import random
import sys
import os
import re
from amara import binderytools
import MySQLdb

config = os.getenv("HACKABOT_CFG")
if (config == None):
	sys.stderr.write("imitate: HACKABOT_CFG is undefined!\n")
	sys.exit(1)

fullcfg = binderytools.bind_file(config).hackabot
database = fullcfg.cmdconfig.database

# Defaults:
maxwords = 40
wordlength = 5
maxlines = 50
limitlines = 200

if hasattr(fullcfg.cmdconfig, 'imitate'):
	imitatecfg = fullcfg.cmdconfig.imitate
	if hasattr(imitatecfg, 'maxwords'):
		maxwords = int(str(imitatecfg.maxwords))
	if hasattr(imitatecfg, 'wordlength'):
		wordlength = int(str(imitatecfg.wordlength))
	if hasattr(imitatecfg, 'maxlines'):
		maxlines = int(str(imitatecfg.maxlines))
	if hasattr(imitatecfg, 'limitlines'):
		limitlines = int(str(imitatecfg.maxlines))

evtype = None
chan = None
nick = None
for line in sys.stdin.readlines():
	if re.match(r'type\s+(\S+)', line):
		c = re.match(r'type\s+(\S+)', line)
		evtype = c.group(1)
	elif re.match(r'to\s+(\S+)', line):
		c = re.match(r'to\s+(\S+)', line)
		chan = c.group(1)
	elif re.match(r'msg\s+(\d+)', line):
		c = re.match(r'msg\s+(\d+)', line)
		maxlines = int(c.group(1))
	elif re.match(r'msg\s+(\S+)', line):
		c = re.match(r'msg\s+(\S+)', line)
		nick = c.group(1)
		c = re.match(r'msg\s+\S+\s+(\d+)', line)
		if c:
			maxlines = int(c.group(1))

if chan == None or evtype == None:
	sys.stderr.write("imitate: chan or event type undefined")
	sys.exit(1)

if evtype != "pubmsg":
	print "send This is not a channel!"
	sys.exit()

if maxlines > limitlines:
	maxlines = limitlines

try:
	db = MySQLdb.connect(host=str(database.host), db=str(database.name), \
			user=str(database.user), passwd=str(database.passwd))
except MySQLdb.Error, e:
	sys.stderr.write("imitate: MySQL error %d: %s" % (e.args[0], e.args[1]))
	sys.exit(1)

max = db.escape_string(str(maxlines))
chan = db.escape_string(chan)
cursor = db.cursor()
if nick:
	nick = db.escape_string(nick)
	nickq = " AND nick = '"+nick+"' "
else:
	nickq = " "
cursor.execute("SELECT id, nick, chan, text, type FROM log WHERE chan = '"+chan+"' AND ( type = 'msg' OR type = 'action' ) "+nickq+" AND text NOT LIKE '!%' ORDER BY id DESC LIMIT "+max)
rows = cursor.fetchall()
cursor.close()
db.close()

text  = "#"*wordlength
rows = [ r for r in rows ]
random.shuffle(rows)
for row in rows:
	line = row[3]
	c = re.match(r'\S+:\s*(.*)', line)
	if c:
		line = c.group(1)
	
	text += " "+string.lower(line)
text += "@"*wordlength

def imitate(word,follow):
    result = ""
    tail = ""
    while follow.has_key(word):
        letter = random.choice(follow[word])
        result += letter
        word += letter
        word = word[1:]
    return result

follow = {}

for i in range(0,len(text)-wordlength):
    word = text[i:i+wordlength]
    char = text[i+wordlength:i+wordlength+1]
    if not follow.has_key(word):
        follow[word] = []
    follow[word].append(char)

seedword = "#"*wordlength

result = imitate(seedword,follow)
while not len(re.split(" ", result)) < maxwords:
    result = imitate(seedword,follow)

imitation = result[:len(result)-wordlength]

if len(imitation) == 0:
	print "send Sorry, I wasn't able to imitate anything."
else:
	print "send", imitation

